package cn.t.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author l
 */
@Slf4j
@Configuration
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int i = Runtime.getRuntime().availableProcessors();
        executor.setCorePoolSize(i);
        executor.setMaxPoolSize(i * 2);
        executor.setQueueCapacity(10000);

        // 线程前缀名，用于区分不同线程池的线程
        executor.setThreadNamePrefix("Ximport cn.t.core.enums.base.BaseStatusEnum;efaultThreadPool-");

        // 当线程空闲时间达到这个值时，如果线程池中的线程数多于核心线程数，则会关闭多余的线程
        executor.setKeepAliveSeconds(60);

        // 线程池对拒绝任务的处理策略，有多种策略可选
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());


        executor.initialize();
        return executor;
    }
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> log.error("Exception handler for async method {}' with parameters {}.", method.getName(), params, ex);
    }
}
